<template>
    <div>
      <navbar></navbar>
      <el-row>

      </el-row>
      <el-card class="box-card">
          <!-- 行内表单 -->
          <div slot="header">
              <el-form v-model="searchForm" :inline="true" class="demo-form-inline">
                  <el-form-item label="设备名称">
                      <el-input v-model="searchForm.deviceName" placeholder="请输入"></el-input>
                  </el-form-item>
                  <el-form-item label="使用状态">
                      <el-select v-model="searchForm.status" placeholder="请选择--">
                        <el-option label="使用中" value="使用中"></el-option>
                        <el-option label="闲置" value="闲置"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                      <el-button type="warning" icon="el-icon-search" @click="searchDeviceList(0)">明细</el-button>
                      <el-tooltip class="item" effect="dark" content="名称和型号都一样的聚合为一条" placement="top-end">
                        <el-button type="warning" icon="el-icon-search" @click="searchDeviceList(1)">聚合查询</el-button>
                      </el-tooltip>
                  </el-form-item>
                  <el-form-item>
                      <el-button type="primary" icon="el-icon-plus" @click="add">添加设备</el-button>
                  </el-form-item>
              </el-form>
          </div>
          <!-- 主体部分的表格 -->
          <el-table :data="tableData" style="width: 100%" :current-row-key="tableData.id" v-loading="page.loading">
              <el-table-column
                  type="index"
                  label="序号"
                  width="50"
              >
              </el-table-column>
              <el-table-column label="名称">
                  <template slot-scope="slotProps">
                      {{slotProps.row.name}}
                  </template>
              </el-table-column>
              <el-table-column label="型号">
                  <template slot-scope="slotProps">
                      {{slotProps.row.model}}
                  </template>
              </el-table-column>
              <el-table-column label="分类">
                  <template slot-scope="slotProps">
                      {{slotProps.row.classify}}
                  </template>
              </el-table-column>
              <el-table-column label="使用状态">
                  <template slot-scope="slotProps">
                      {{slotProps.row.status}}
                  </template>
              </el-table-column>
              <el-table-column label="创建时间">
                  <template slot-scope="slotProps">
                      {{slotProps.row.createTime}}
                  </template>
              </el-table-column>
              <el-table-column label="所在实验室">
                  <template slot-scope="slotProps">
                      {{slotProps.row.lab}}
                  </template>
              </el-table-column>

              <el-table-column v-if="group==1" label="数量">
                  <template slot-scope="slotProps">
                      {{`${slotProps.row.count}件`}}
                  </template>
              </el-table-column>

              <el-table-column label="操作" width="160">
                  <template slot-scope="slotProps" v-if="!slotProps.row.count || slotProps.row.count <= 1">
                      <el-button type="primary" size="mini" title="编辑" icon="el-icon-edit" @click="edit(slotProps.$index)"></el-button>
                      <el-button type="danger" size="mini" title="删除" icon="el-icon-delete" @click="del(slotProps.$index)"></el-button>
                  </template>
              </el-table-column>
          </el-table>
          <br>
          <div class="pagination">
              <el-pagination
                  background
                  layout="total, prev, pager, next, jumper"
                  :pager-count="5"
                  :total="page.total"
                  :page-size="page.pageSize"
                  :current-page="page.currentPage"
                  @current-change="handleCurrentChange"
              >
              </el-pagination>
          </div>
      </el-card>
      <!-- 点击删除时的弹框 -->
      <el-dialog
          :title="delDialog.title"
          :visible.sync="delDialog.show"
          width="400px"
          center>
          <span>{{delDialog.content}}</span>
          <span slot="footer">
              <el-button @click="delDialog.show = false">取 消</el-button>
              <el-button type="primary" @click="delSure">确 定</el-button>
          </span>
      </el-dialog>
      <!-- 点击添加、编辑时的弹框 -->
      <el-dialog
          :title="dialog.isEdit?'编辑':'添加'"
          :visible.sync="dialog.show"
          @close="handleDialogClose(`formData`)"
          width="800px"
          center>
          <el-form ref="formData" :rules="ruleForm" :model="formData" label-width="80px">
              <el-form-item label="设备名称" prop="name">
                  <el-input placeholder="请输入设备名称" v-model="formData.name"></el-input>
              </el-form-item>
              <el-form-item label="设备型号" prop="model">
                  <el-input placeholder="请输入设备型号" v-model="formData.model"></el-input>
              </el-form-item>

              <el-form-item label="设备分类" prop="typeId">
                  <el-autocomplete v-model="formData.classify" value-key="name" :fetch-suggestions="filterTypeSearch" placeholder="请输入设备分类"></el-autocomplete>
              </el-form-item>
              <el-form-item label="存放地" prop="lab">
                  <el-autocomplete v-model="formData.lab" value-key="name" :fetch-suggestions="filterLabSearch" placeholder="请输入存放地"></el-autocomplete>
              </el-form-item>

              <el-form-item label="数量" prop="count" v-if="!dialog.isEdit">
                  <el-input-number v-model="formData.count" controls-position="right" :min="0"></el-input-number>
              </el-form-item>
              <el-form-item label="使用状态" prop="status">
                  <el-select v-model="formData.status" placeholder="请选择--">
                      <el-option label="使用中" value="使用中"></el-option>
                      <el-option label="闲置" value="闲置"></el-option>
                  </el-select>
              </el-form-item>
              <!-- <el-form-item label="价格" prop="price">
                  <el-input placeholder="请输入价格" type="number" v-model="formData.price">
                      <template slot="prepend">￥</template>
                      <template slot="append">元</template>
                  </el-input>
              </el-form-item> -->
              <el-form-item>
                  <el-button @click="dialog.show = false">取 消</el-button>
                  <el-button v-if="dialog.isEdit" type="primary" @click="editSure('formData')">提 交</el-button>
                  <el-button v-else type="primary" @click="addSure('formData')">添 加</el-button>
                  <el-button @click="resetForm('formData')">重 置</el-button>
              </el-form-item>
          </el-form>
      </el-dialog>
    </div>
</template>
<script>
import { default as Navbar } from './Navbar'
import request from '@/utils/request'
export default {
  data() {
    return {
      activeIndex: '1',
      group: 0,
      tableData: [],
      page: {
        total: 10,
        pageSize: 10,
        currentPage: 1,
        loading: false
      },
      dependencyList: { // 依赖相关
        deviceTypeList: [], // 设备分类列表
        addressList: [] // 存放地列表
      },
      searchForm: {
        status: '',
        deviceName: ''
      },
      delDialog: {
        show: false,
        title: '提示',
        content: '您确定要删除当前设备吗？',
        currentId: ''
      },
      dialog: {
        show: false,
        title: '编辑',
        index: '',
        isEdit: false
      },
      formData: {}, // 表单中的数据
      resetData: {}, // 重置表单的数据
      ruleForm: { // 表单验证
        name: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        model: [
          { required: true, message: '请输入设备型号', trigger: 'blur' }
        ],
        classify: [
          { required: true, message: '请选择设备分类', trigger: 'change' }
        ],
        lab: [
          { required: true, message: '请选择存放地', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择使用状态', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    Navbar
  },
  mounted() {
    this.getList()
    // 获取下拉框依赖列表，设备分类
    request.get('/items/deviceType').then(res => {
      console.log('设备类型：', res)
      this.dependencyList.deviceTypeList = res.content.list
    })
    // 获取下拉框依赖列表，存放地
    request.get('/items/address').then(res => {
      this.dependencyList.addressList = res.content
    })
  },
  methods: {
    // 翻页器
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList()
    },
    // 初始化列表
    getList(current, group = 0) {
      this.page.loading = true
      request.get('/lab/devices', { params: {
        size: this.page.pageSize,
        current: this.page.currentPage,
        status: this.searchForm.status,
        name: this.searchForm.deviceName,
        group: group
      }}).then(res => {
        this.tableData = res.content.records
        this.page.total = res.content.total
        this.group = group
        this.page.loading = false
      })
    },
    // 根据一定条件查询设备列表
    searchDeviceList(group) {
      this.getList(1, group)
    },
    // 根据id查询详细信息
    getDetail(id) {
      request.get(`/lab/devices/${id}`).then(res => {
        this.formData = res.content
        this.resetData = { ...this.formData }
      })
    },
    // 删除设备
    del(index) {
      this.delDialog.show = true
      this.delDialog.currentId = this.tableData[index].id
    },
    delSure() {
      request.delete(`/lab/devices/${this.delDialog.currentId}`).then(() => {
        this.getList()
        this.delDialog.show = false
      })
    },
    // 添加设备
    add() {
      this.formData = { status: '使用中', count: 1 }
      this.dialog.show = true
      this.dialog.isEdit = false
    },
    addSure(formName) {
      const addData = { ...this.formData }
      this.$refs[formName].validate(valid => {
        if (valid) {
          request.post(`lab/devices?count=${addData.count}`, {
            ...addData
          }).then(res => {
            if (res.code === 0) {
              this.getList()
              this.$message.success('添加成功')
            } else {
              this.$message.error(res.content)
            }
            this.dialog.show = false
          })
        }
      })
    },
    // 编辑某一个设备
    edit(index) {
      this.dialog.show = true
      this.dialog.isEdit = true
      this.dialog.index = index
      this.getDetail(this.tableData[index].id)
    },
    editSure(formName) {
      var editData = { ...this.formData }
      this.$refs[formName].validate(valid => {
        if (valid) { // 若表单内容通过验证规则，则提交表单，反之，不提交
          request.put('/lab/devices', {
            id: this.tableData[this.dialog.index].id,
            ...editData
          }).then(res => {
            if (res.code === 0) {
              this.getList()
              this.$message.success('修改成功')
            } else {
              this.$message.error(res.content)
            }
            this.dialog.show = false
          })
        }
      })
    },
    // Dialog关闭的回调
    handleDialogClose(formName) {
      this.$refs[formName].resetFields()
    },
    // 当多选框的绑定值发生变化后触发的事件 CHeckbox-group Events
    handleCheckboxChange(value) {
      if (!this.dialog.isEdit) { // 添加的时候调用
        this.formData.roleids = [...value]
      }
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields() // 此处用this.$refs[formName].resetFields()后会把表单置空的原因是初始data里的数据就是空的
      this.formData = { ...this.resetData }
    },
    // 设备分类建议
    filterTypeSearch(queryString, cb) {
      const typeList = this.dependencyList.deviceTypeList
      const results = queryString ? typeList.filter(this.createFilter(queryString)) : typeList
      console.log(results)
      cb(results)
    },
    // 存放地建议
    filterLabSearch(queryString, cb) {
      const typeList = this.dependencyList.addressList
      const results = queryString ? typeList.filter(this.createFilter(queryString)) : typeList
      console.log(results)
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) !== -1)
      }
    }
  }
}
</script>

<style scoped>
.pagination {
  float: right;
  margin-bottom: 15px;
}
.box-card {
  width: 90%;
  margin: 20px auto;
}
</style>
